const Path = require("path");
const glob = require("glob");
const HappyPack = require("happypack");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const PurgecssPlugin = require("purgecss-webpack-plugin");
const BasePlugins = require("./webpack.plugins");

const { resolve } = Path;

const PATHS = {
  src: Path.join(__dirname, "src"),
};

module.exports = {
  output: {
    filename: "js/[name]-[chunkhash:6].js",
    chunkFilename: "js/[name]-[chunkhash:6].js",
    path: resolve(__dirname, "dist"),
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        use: ["vue-loader"],
      },
      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          "css-loader",
          {
            loader: "postcss-loader",
            options: {
              plugins: () => [
                require("autoprefixer")({
                  overrideBrowserslist: ["last 2 version", ">1%", "ios 7"],
                }),
              ],
            },
          },
        ],
      },
      {
        test: /\.less$/,
        use: [
          MiniCssExtractPlugin.loader,
          "css-loader",
          "less-loader",
          {
            loader: "postcss-loader",
            options: {
              plugins: () => [
                require("autoprefixer")({
                  overrideBrowserslist: ["last 2 version", ">1%", "ios 7"],
                }),
              ],
            },
          },
        ],
      },
      {
        test: /\.js$/,
        use: ["happypack/loader?id=babel"],
        exclude: /node_modules/,
      },
      {
        test: /\.(jpg|jpeg|png|gif)$/,
        use: [
          {
            loader: "url-loader",
            options: {
              esModule: false,
              limit: 8192,
              outputPath: "img/",
              name: "[name]-[chunkhash:6].[ext]",
            },
          },
        ],
      },
      {
        test: /\.(woff|woff2|svg|eot|ttf)$/,
        use: [
          {
            loader: "file-loader",
            options: {
              outputPath: "fonts/",
              name: "[name].[ext]",
            },
          },
        ],
      },
    ],
  },
  plugins: [
    ...BasePlugins,
    new HappyPack({
      id: "babel",
      loaders: ["babel-loader?cacheDirectory=true"],
    }),
    new MiniCssExtractPlugin({
      filename: "[name]_[contenthash:8].css",
    }),
    new PurgecssPlugin({
      paths: glob.sync(`${PATHS.src}/**/*`,  { nodir: true }),
    })
  ],
  cache: {
    type: "filesystem",
    buildDependencies: {
      config: [__filename],
    },
    version: "1.0",
  },
  resolve: {
    extensions: [".js", ".json", ".css", ".less", ".vue"],
    alias: {
      vue$: "vue/dist/vue.common.js",
      "@": resolve(__dirname, "./src"),
    },
  },
};
